package com.vilen.cms.service;

import com.vilen.basic.model.SystemContext;
import com.vilen.cms.dao.ChannelDao;
import com.vilen.cms.model.Channel;
import com.vilen.cms.model.ChannelTree;
import com.vilen.cms.model.CmsException;
import org.springframework.stereotype.Service;

import javax.inject.Inject;
import java.util.List;

/**
 * Created by vilen on 2017/2/12.
 */
@Service("channelService")
public class ChannelService implements IChannelService{
    private ChannelDao channelDao;

    public ChannelDao getChannelDao() {
        return channelDao;
    }

    @Inject
    public void setChannelDao(ChannelDao channelDao) {
        this.channelDao = channelDao;
    }

    @Override
    public void add(Channel channel, Integer pid) {
        Integer orders = channelDao.getMaxOrderByParent(pid);

        if (pid != null && pid > 0) {
            Channel pc = channelDao.load(pid);
            if (pc == null) {
                throw new CmsException("要添加栏目的父类对象不正确!");
            }
            channel.setParent(pc);
        }
        channel.setOrders(orders+1);
        channelDao.add(channel);
    }

    @Override
    public void update(Channel channel) {
        channelDao.update(channel);
    }

    @Override
    public void delete(int id) {
        // 是否存在子栏目
        List<Channel> channelList = channelDao.listByParent(id);
        if (channelList != null && channelList.size()>0) {
            throw new CmsException("要删除的栏目还有子栏目,无法删除!");
        }
        // 是否存在文章

        // 需要删除和组的关系

        channelDao.delete(id);
    }

    @Override
    public void clearTopic(int id) {

    }

    @Override
    public Channel load(int id) {
        return channelDao.load(id);
    }

    @Override
    public List<Channel> listByParent(Integer pid) {
//        String sort = SystemContext.getSort();
//        if (sort == null || "".equals(sort.trim())) {
//            SystemContext.setSort("orders");
//            SystemContext.setOrder("asc");
//        }
        return channelDao.listByParent(pid);
    }

    @Override
    public List<ChannelTree> generateTree() {
        return channelDao.generateTree();
    }

    @Override
    public List<ChannelTree> generateTreeByParent(Integer pid) {
        return channelDao.generateTreeByParent(pid);
    }

    @Override
    public void updateSort(Integer[] ids) {
        channelDao.udpateSort(ids);
    }
}
